function columnToSQL(col, sqlMapper) {
    if (!col) {
        return col
    }
    if (!sqlMapper) {
        return col;
    }
    let colMapper = getColTypMapper(col, sqlMapper);
    if (!col.sqlDataType) {
        col.sqlDataType = colMapper.sqlDataType
    }
    if (!col.sqlDataLength) {
        col.sqlDataLength = colMapper.sqlDataLength
    }
    return col;
}


function getColType(col) {
    let type = col.type || col.component
    return type || "input"
}


function isInvalid(val) {
    if (val === undefined) {
        return true
    }
    return val === null;
}

function isEffective(val) {
    return !isInvalid(val)
}

/**
 * 获取组件类型映射的sql 配置
 * @param col
 * @param sqlMapper
 * @returns {{}}
 */
function getColTypMapper(col, sqlMapper) {
    const type = getColType(col);
    let result = {};
    result.sqlDataType = col.sqlDataType;
    result.sqlDataLength = col.sqlDataLength;
    result.sqlDisabled = col.sqlDisabled;
    let colMapper = sqlMapper[type]
    if (isInvalid(colMapper)) {
        return result;
    }
    if (isInvalid(result.sqlDataType)) {
        result.sqlDataType = isEffective(colMapper.sqlDataType) ? colMapper.sqlDataType : sqlMapper.defSqlDataType
    }
    if (isInvalid(result.sqlDataLength)) {
        result.sqlDataLength = isEffective(colMapper.sqlDataLength) ? colMapper.sqlDataLength : sqlMapper.defSqlDataLength
    }
    if (isInvalid(result.sqlDisabled)) {
        result.sqlDisabled = isEffective(colMapper.sqlDisabled) ? colMapper.sqlDisabled : sqlMapper.defSqlDisabled
    }
    return result
}

function createCol(col, sqlMapper) {
    let colMapper = getColTypMapper(col, sqlMapper);
    
    col.sqlDataType = colMapper.sqlDataType
    col.sqlDataLength = colMapper.sqlDataLength;
    col.sqlDisabled = colMapper.sqlDisabled;
    return col
}


function formOptionToSQL(option, sqlMapper) {
    if (!option || !option.column || option.column.length < 1) {
        return option;
    }
    if (!sqlMapper) {
        return option
    }
    let defType = sqlMapper.defSqlDataType || 'varchar';
    let defLen = sqlMapper.defSqlDataLength || 0;
    for (let i = 0; i < option.column.length; i++) {
        let col = option.column[i];
        if (col.sqlType) {
            continue
        }
        if (col.type === 'dynamic') {
            col.children = formOptionToSQL(col.children, sqlMapper)
            continue
        }

        option.column[i] = columnToSQL(col, sqlMapper, defType, defLen)
    }
    return option;
}

function createProp() {
    return "field" + '_' + Math.ceil(Math.random() * 99999)
}

const startColMapperTools = {
    formOptionToSQL,
    createCol,
    createProp,

}
export default startColMapperTools
